<?php

namespace frontend\controllers;

use bc\controller\FrontController;
use bc\wx\pay\PayNotifyCallBack;
use bc\model\wx\PayLog;
use bc\model\wc\BookingModel;
use bc\model\OrderModel;

class WxnotifyController extends FrontController
{
	public function actionNotify()
	{
		$xml = file_get_contents('php://input');
		
		$xmlObj = simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA);
		
		$payLog = new PayLog();
		$log = $payLog->getRow(['transaction_id' => $xmlObj->transaction_id, 'status_code' => $xmlObj->result_code]);
		if(!$log)
		{
			$orderNo = $xmlObj->out_trade_no;
			$orderNo = str_replace('zsmm', '', $orderNo);
			
			$data['openid'] = $xmlObj->openid;
			$data['transaction_id'] = $xmlObj->transaction_id;
			$data['status_code'] = $xmlObj->result_code;
			$data['create_time'] = time();
			$data['order_no'] = $orderNo;
			$payLog->add($data);
		}
		
		if($xmlObj->result_code == 'SUCCESS' && $xmlObj->return_code == 'SUCCESS')
		{
			//普通订单操作
			$orderModel = new OrderModel();
			$orderModel->autoId = 'order_id';
			$orderNo = $xmlObj->out_trade_no;
			$orderNo = str_replace('zsmm', '', $orderNo);
			$order = $orderModel->getRow(['order_no' => $orderNo, 'order_status' => 1, 'pay_status' => 0]);
			if($order)
			{
				$orderModel->modify(['order_status' => 2, 'pay_status' => 1, 'pay_time' => time()], $order['order_id']);
			}
			
			//预约单操作
			$bookingModel = new BookingModel();
			$bookingRow = $bookingModel->getRow(['openid' => $xmlObj->openid, 'order_no' => $orderNo]);
			
			if($bookingRow['status'] == 1)
			{
				$bookingModel->modify(['status' => 2], $bookingRow['id']);
			}
			
			
			
		}
		
		
		$notify = new PayNotifyCallBack();
		$notify->Handle(false);
	}
	
	
	
	/**
	 * 
	 * @param string $date
	 * @return int
	 */
	protected function timeToInt($date)
	{
		$format_date = preg_replace("/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/", '$1-$2-$3 $4:$5:$6' ,$date);
		return strtotime( $format_date);
	}
}

